package com.interview.c_死锁.a_转账;

/**
 * A 转账给 B
 * 放开注释 出现死锁
 * <p>
 * * 死锁的四个条件
 * * 1.互斥
 * * 2.保持并请求
 * * 3.不可取消
 * * 4.形成闭环
 */
public class Transfer implements Runnable {
    private int flag = 1;
    static Account a = new Account("A", 1000);
    static Account b = new Account("B", 1000);

    @Override
    public void run() {

        //        A 转给 B
        if (flag == 1) {
            transferMoney(a, b, 500);
        }

        //        B 转给 A
        if (flag == 2) {
            transferMoney(b, a, 500);
        }
    }

    public static void transferMoney(Account from, Account to, int money) {
        synchronized (from) {
//            System.out.println(from.name + " 获取到 " + from.name + "锁");
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (to) {
                if (from.money < money) {
                    System.out.println("用户：" + from.name + "，余额不足 " + money + " \n");
                    return;
                }
                from.money -= money;
                to.money += money;
                System.out.println();

                System.out.println(from.name + "转账给" + to.name + "  " + money + "￥成功！    " + from.name + "剩余 ：" + from.money + "  ， " + to.name + "剩余：" + to.money);
            }
        }

    }


    public static void main(String[] args) throws InterruptedException {

        Transfer transferA = new Transfer();
        transferA.flag = 1;
        Thread threadA = new Thread(transferA);
        threadA.start();


        Transfer transferB = new Transfer();
        transferB.flag = 2;
        Thread threadB = new Thread(transferB);
        threadB.start();

        threadA.join();
        threadB.join();


        System.out.println(a.name + "剩余 " + a.money);
        System.out.println(b.name + "剩余 " + b.money);
    }

}

